package cn.jbolt.ai.app.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.jbolt.ai.app.entity.AiApp;
import cn.jbolt.ai.app.vo.AiChatData;
import cn.jbolt.ai.app.vo.ActionData;
import cn.jbolt.ai.klb.entity.AiDoc;
import cn.jbolt.ai.klb.service.AiDocService;
import cn.jbolt.util.JSONUtil;
import cn.jbolt.util.Pager;
import cn.jbolt.util.Result;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.jbolt.ai.app.dao.AiAppMessageMapper;
import cn.jbolt.ai.app.entity.AiAppMessage;
import cn.jbolt.ai.app.service.AiAppMessageService;
import com.fasterxml.jackson.databind.node.ArrayNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class AiAppMessageServiceImpl extends ServiceImpl<AiAppMessageMapper, AiAppMessage> implements AiAppMessageService {

    @Autowired
    private AiDocService aiDocService;

    @Override
    public Result deleteMsgByAppId(Long appId) {
        QueryWrapper<AiAppMessage> wrapper = new QueryWrapper<AiAppMessage>().eq("app_id", appId);
        List<AiAppMessage> list = this.list(wrapper);
        if (list.size() > 0) {
            if (!this.remove(wrapper)) {
                return Result.error("删除失败");
            }
        }
        return Result.success();
    }

    @Override
    public Result add(AiAppMessage appMessage) {
        if (this.save(appMessage)) {
            return Result.success(appMessage);
        }
        return Result.error("添加失败");
    }

    @Override
    public Result update(AiAppMessage appMessage) {
        if (appMessage.getMsgCache() != null) {
            appMessage.setContent(JSONUtil.toJson(appMessage.getMsgCache()));
        }
        if (this.updateById(appMessage)) {
            return Result.success();
        }
        return Result.error("更新失败");
    }







    @Override
    public Result updateLinkId(Long LinkId, Long id) {
        if (this.update(new UpdateWrapper<AiAppMessage>().set("link_id", LinkId).eq("id", id))) {
            return Result.success();
        }
        return Result.error("更新失败");
    }

    @Override
    public Result getSessionContextMsg(Long sessionId, Long startId,  Integer limit) {
        limit = (limit != null && limit > 0) ? limit : 20;
        QueryWrapper<AiAppMessage> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("app_session_id", sessionId).orderByDesc("id");
        if (startId != null) queryWrapper.lt("id", startId);
        queryWrapper.last("limit " + limit);
        List<AiAppMessage> list = this.list(queryWrapper);
        Optional.ofNullable(list)
                .ifPresent(l -> l.sort((m1, m2) -> m1.getId().compareTo(m2.getId())));
        return Result.success(list);
    }

    /**
     * 生成问题跟答案这两个对象,存储数据,并把二者数据关联到一起,
     * 把提问和回答组成一个数组返回
     *
     * @return
     */
    public Result<AiAppMessage[]> addMessageReturnAnswer(ActionData chatVO, String answer, AiApp aiApp, Long sessionId) {
        // 创建并添加提问消息
        AiChatData data = chatVO.getDataAsChatData();

        AiAppMessage askMessage = createRequestMessage(sessionId, aiApp.getId(), data);

        Result askResult = add(askMessage);
        if (askResult.isError()) {
            return askResult;
        }
        // 模拟回答问题

        AiAppMessage answerMessage = createResponseMessage(sessionId, answer, askResult, aiApp.getId());
        Result questionResult = add(answerMessage);
        if (questionResult.isError()) {
            return questionResult;
        }
        // 更新提问消息的关联链接
        updateLinkId(askMessage, questionResult);
        return Result.success(new AiAppMessage[]{askMessage, answerMessage});
    }


    public Result<AiAppMessage[]> regenerateMsg(Long msgId, String defaultContent) {
        AiAppMessage answerMsg = getById(msgId);
        if (answerMsg == null) {
            return Result.error("消息不存在");
        }
        AiAppMessage askMsg = getById(answerMsg.getLinkId());
        if (askMsg == null) {
            return Result.error("提问消息不存在");
        }
        answerMsg.setContent(defaultContent);
        answerMsg.setDocs(null);
        answerMsg.setStatus(null);
        answerMsg.setCreateTime(new Date());
        answerMsg.setErrorMsg(null);
        update(answerMsg);
        return Result.success(new AiAppMessage[]{askMsg, answerMsg});

    }

    /**
     * 创建提问类型的AiMessage对象
     *
     * @param sessionId 会话ID

     * @return 构建好的AiMessage对象
     */
    private AiAppMessage createRequestMessage(Long sessionId,Long appId,AiChatData data ) {
        AiChatData.AiChatContent content = data.getContent();
        AiAppMessage askMessage = new AiAppMessage();
        askMessage.setAppId(appId);
        askMessage.setAppSessionId(sessionId);
        askMessage.setContent(content.getText());
        askMessage.setRole(data.getRole());
        askMessage.setImgs(JSONUtil.toJson(content.getImgs()));
        return askMessage;
    }

    /**
     * 创建回答类型的AiMessage对象，并设置关联的提问消息ID
     *
     * @param sessionId 会话ID
     * @param answer    回答内容
     * @param askResult 提问消息添加后的结果，用于获取提问消息的ID
     * @return 构建好的回答类型的AiMessage对象
     */
    private AiAppMessage createResponseMessage(Long sessionId, String answer, Result askResult, Long appId) {
        AiAppMessage answerMessage = new AiAppMessage();
        answerMessage.setAppSessionId(sessionId);
        answerMessage.setAppId(appId);
        answerMessage.setContent(answer);
        answerMessage.setRole(AiChatData.ROLE_ASSISTANT);
        answerMessage.setLinkId(((AiAppMessage) askResult.getData()).getId());
        return answerMessage;
    }



    /**
     * 更新提问消息的关联链接ID
     *
     * @param askMessage     提问消息对象
     * @param questionResult 回答消息添加后的结果，用于获取回答消息的ID
     */
    private Result updateLinkId(AiAppMessage askMessage, Result questionResult) {
        if (questionResult.isError()) {
            return questionResult;
        }
        AiAppMessage msg = (AiAppMessage) questionResult.getData();
        return updateLinkId(msg.getId(), askMessage.getId());

    }
    @Override
    public Result listByPage(String sessionId, Long startId, Integer pageSize) {
        // 检查分页参数
        if (pageSize == null || pageSize <= 0 || StrUtil.isEmpty(sessionId)) return Result.error("参数异常");
        QueryWrapper<AiAppMessage> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("app_session_id", sessionId).orderByDesc("id");
        if (startId != null) queryWrapper.lt("id", startId);
        queryWrapper.last("limit " + pageSize);
        List<AiAppMessage> list = this.list(queryWrapper);
        for (AiAppMessage msg : list) {
            if (StrUtil.isBlank(msg.getDocs())) continue;
            //处理关联的文档资料
            List<String> docIds = JSONUtil.toObjectList(msg.getDocs(), String.class);
            List<AiDoc> docs = aiDocService.getDocListByIds(docIds);
            ArrayNode refers = JSONUtil.createArrayNode();
            for (AiDoc doc : docs) {
                refers.add(doc.convertToReference());
            }
            msg.setReference(refers);
        }
        //现在是倒序,要变成升序
        Optional.ofNullable(list)
                .ifPresent(l -> l.sort((m1, m2) -> m1.getId().compareTo(m2.getId())));

        Page page = new Page(0, pageSize, this.count());
        page.setRecords(list);
        return Result.success(Pager.from(page));

    }

    @Override
    public Result delete(Long sessionId) {
        List<AiAppMessage> list = this.list(new QueryWrapper<AiAppMessage>().eq("app_session_id", sessionId));
        if (list.size() > 0) {
            if (this.remove(new QueryWrapper<AiAppMessage>().eq("app_session_id", sessionId))) {
                return Result.success();
            }
            return Result.error("删除失败");
        }
        return Result.success();
    }

    /**
     * 根据消息的id,移除问题跟答案这两条记录
     *
     * @param msgId
     * @return
     */
    @Override
    @Transactional
    public Result delMsgById(Long msgId) {
        AiAppMessage answer = this.getById(msgId);
        if (answer != null) {
            AiAppMessage question = this.getById(answer.getLinkId());
            if(question!=null){
                if (this.removeById(msgId)) {
                    if (this.removeById(answer.getLinkId())) {
                        return Result.success("删除成功");
                    }
                }
                return Result.error("删除失败");
            }
        }
        return Result.error("删除失败,该消息不存在!");

    }
}
